<template>
  <Scroll class="suggest"
          :data='result'
          :pullup='true'
          :beforeScroll='true'
          @beforeScroll='listScroll'
          @scrollToEnd='searchMore'
          ref='suggest'
  >
    <ul class='suggest-list'>
      <li @click='selectItem(item)' class='suggest-item' v-for='item in result'>
        <div class='icon'>
          <i :class='getIconClis(item)'></i>
        </div>
        <div class='name'>
          <p class='text' v-html='getDisplayName(item)'></p>
        </div>
      </li>
      <loading v-show="hasMore" title=""></loading>
    </ul>
    <div class='no-result-wrapper' v-show='!hasMore && !result.length'>
      <no-result :title='title'></no-result>
    </div>
  </Scroll>
</template>

<script>
  import { search, searchSuggest } from 'api'
  import { createSearchSong } from 'common/js/song'
  import Scroll from 'base/scroll/scroll'
  import Loading from 'base/loading/loading'
  import Singer from 'common/js/singer'
  import NoResult from 'components/no-result/no-result'
  import { mapMutations, mapActions } from 'vuex'
  import { SET_SINGER } from '../../store/mutation-types'

  const TYPE_SINGER = 'singer'
  const PAGE_OFFSET = 30

  export default {
    props: {
      query: {
        type: String,
        default: ''
      },
      showSinger: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        page: 0,
        result: [],
        hasMore: true,
        title: '暂无内容'
      }
    },
    methods: {
      refresh(){
        this.$refs.suggest.refresh()
      },
      search() {
        this.page = 0
        this.hasMore = true
        this.$refs.suggest.scrollto(0, 0, 0)
        if (!this.query) {
          this.result = []
          return
        }
        search({ keywords: this.query, offset: this.page * PAGE_OFFSET }).then((res) => {
          if (res.data.result.songs && res.data.result.songs.length) {
            this._genSongResult(res.data.result.songs)
          } else {
            this.result = []
          }
          this._checkMore(res.data.result)
        })
        if (this.showSinger) {
          searchSuggest({ keywords: this.query }).then((res) => {
            let singer = []
            if (res.data.result.artists && res.data.result.artists.length) {
              singer.push({ ...res.data.result.artists[0], ...{ type: TYPE_SINGER } })
              this._genSinger(singer)
            }
          })
        }
      },
      getIconClis(item) {
        if (item.type === TYPE_SINGER) {
          return 'icon-mine'
        } else {
          return 'icon-music'
        }
      },
      getDisplayName(item) {
        if (item.type === TYPE_SINGER) {
          return item.name
        } else {
          return `${item.name}-${item.singer}`
        }
      },
      searchMore() {
        console.log(this.hasMore)
        if (!this.hasMore) {
          return
        }
        this.page++
        search({ keywords: this.query, offset: this.page * PAGE_OFFSET }).then((res) => {
          if (res.data.result.songs && res.data.result.songs.length) {
            this._genSongResult(res.data.result.songs)
          }
          this._checkMore(res.data.result)
        })
      },
      selectItem(item) {
        if (item.type === TYPE_SINGER) {
          let singer = new Singer(
            item.id,
            item.name,
            item.picUrl
          )
          this.$router.push({
            path: `/search/${item.id}`
          })
          this.setSinger(singer)
        } else {
          this.insertSong(item)
        }
        this.$emit('select')
      },
      listScroll() {
        this.$emit('listScroll')
      },
      _checkMore(data) {
        const song = data.songs
        const count = data.songCount
        if (!song || !song.length || (this.page + 1) * PAGE_OFFSET >= count) {
          this.hasMore = false
        }
      },
      _genSongResult(song) {
        let songList = []
        song.forEach((item) => {
          if (item.id && item.album.id) {
            songList.push(createSearchSong(item))
          }
        })
        this.result = this.result.concat(songList)
      },
      _genSinger(singer) {
        this.result.unshift(singer[0])
      },
      ...mapMutations({
        setSinger: SET_SINGER
      }),
      ...mapActions([
        'insertSong'
      ])
    },
    watch: {
      query() {
        this.search()
      }
    },
    components: {
      Scroll,
      Loading,
      NoResult
    }
  }
</script>

<style lang="stylus" scoped>
  @import "~common/stylus/variable"
  @import "~common/stylus/mixin"

  .suggest
    height: 100%
    overflow: hidden
    .suggest-list
      padding: 0 30px
      .suggest-item
        display: flex
        align-items: center
        padding-bottom: 20px
      .icon
        flex: 0 0 30px
        width: 30px
        /*选择CLASS名是以icon-开头的元素*/
        [class^="icon-"]
          font-size: 14px
          color: $color-text-d
      .name
        flex: 1
        font-size: $font-size-medium
        color: $color-text-d
        overflow: hidden
        .text
          no-wrap()
    .no-result-wrapper
      position: absolute
      width: 100%
      top: 50%
      transform: translateY(-50%)
</style>
